/**
 * @author YUN
 */
package sample.provider.ddl;

import android.text.TextUtils;

/**
 * @author YUN
 */
public class SQLiteTable extends SQLiteObject {
    public static final String COLUMN_CONSTRAINT_PRIMARY_KEY = "PRIMARY KEY AUTOINCREMENT NOT NULL";

	public SQLiteTable(String name) {
		super(name);
	}

	public SQLiteTable addIntegerColumn(String columnName) {
		return addIntegerColumn(columnName, null);
	}

	public SQLiteTable addIntegerColumn(String columnName, String columnConstraint) {
		add(columnName + " INTEGER", columnConstraint);
		return this;
	}

	public SQLiteTable addTextColumn(String columnName) {
		return addTextColumn(columnName, null);
	}

	public SQLiteTable addTextColumn(String columnName, String columnConstraint) {
		add(columnName + " TEXT", columnConstraint);
		return this;
	}

	public SQLiteTable addNumericColumn(String columnName) {
		return addNumericColumn(columnName, null);
	}

	public SQLiteTable addNumericColumn(String columnName, String columnConstraint) {
		add(columnName + " NUMERIC", columnConstraint);
		return this;
	}

	public SQLiteTable addBlobColumn(String columnName) {
		return addBlobColumn(columnName, null);
	}

	public SQLiteTable addBlobColumn(String columnName, String columnConstraint) {
		add(columnName + " BLOB", columnConstraint);
		return this;
	}

	@Override
	String toDropSql() {
		return "DROP TABLE IF EXISTS " + getName();
	}

	@Override
	String toCreateSql() {
		StringBuilder sql = new StringBuilder();
		// start
		sql.append("CREATE TABLE INDEX IF NOT EXISTS ").append(getName()).append('(');
		// contents
		boolean addComma = false;
		for (String part : getColumn()) {
			if (addComma) {
				sql.append(',');
			}
			addComma = true;
			sql.append('\n').append(part);
		}
		// end
		sql.append('\n').append(");");
		return sql.toString();
	}

	private void add(String columnPart, String constraintPart) {
		if (TextUtils.isEmpty(constraintPart)) {
			addColumn(columnPart);
		} else {
			addColumn(columnPart + " " + constraintPart);
		}
	}
}
